package com.example.librarymanagementproject2.web.controller;

import com.example.librarymanagementproject2.Common.config.ResultVO;
import com.example.librarymanagementproject2.Common.utils.MinioUtil;
import com.example.librarymanagementproject2.model.dto.LoginResult;
import com.example.librarymanagementproject2.model.dto.UserRegisterDTO;
import com.example.librarymanagementproject2.model.entity.User;
import com.example.librarymanagementproject2.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName LoginController
 * @Description TODO
 * @Author Kx
 * @Date 2025/10/10 20:28
 * @Version 1.0
 */
@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private MinioUtil minioUtil;

    /**
     * @author: kx
     * @date: 2025/10/26 20:24
     * @param user : 用户信息
     * @param image : 头像图片
     * @param captcha : 验证码
     * @param confirmPassword : 确认密码
     * @return com.example.librarymanagementproject2.Common.config.ResultVO<java.lang.String>
     * @description: 注册用户信息
    */
    @PutMapping("/users")
    public ResultVO<String> addUser(
            @RequestPart("user") User user,  // 接收用户信息（JSON格式）
            @RequestPart("image") MultipartFile image,  // 接收文件
            @RequestParam("captcha") String captcha,
            @RequestParam("confirmPassword") String confirmPassword
    ) {
        // 手动构建UserRegisterDTO
        UserRegisterDTO dto = new UserRegisterDTO();
        dto.setUser(user);
        dto.setImage(image);
        dto.setCaptcha(captcha);
        dto.setConfirmPassword(confirmPassword);

        String fileName;

        // 判断文件是否为空
        if (image == null || image.isEmpty()) {
            // 如果为空则使用默认头像
            fileName = "...";
        } else {
            // 上传图片
            fileName = minioUtil.uploadImage(dto.getImage());
        }
        user.setImage(fileName);
        loginService.addUser(dto);
        return ResultVO.success("注册成功");
    }

    /**
     * @author: kx
     * @date: 2025/9/29 15:49
     * @param username : 用户名
     * @param password : 密码
     * @return org.example.common.config.ResultVO<org.example.model.entity.User>
     * @description: 用户登录
     */
    @PostMapping("/login")
    public ResultVO<LoginResult> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        LoginResult token = loginService.login(username, password);
        return ResultVO.success(token);
    }
}
